package com.sec.etech.ism.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.file.service.EtechFileHandlerService;
import com.sec.etech.file.service.EtechWebUploaderService;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmTaskService;
import com.sec.etech.nc.service.NcService;
import com.sec.etech.org.service.EtechUserUtil;
import com.sec.etech.sys.util.ContextUtil;
import com.sec.etech.sys.util.DbUtil;
import com.sec.etech.sys.util.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.core.id.IdUtil;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.org.api.model.IUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsmGetNcFileByNumServiceImpl implements IsmMethodService {
    @Resource
    NcService ncService;
    @Resource
    EtechWebUploaderService webUploaderService;
    @Resource
    EtechFileHandlerService fileHandlerService;
    @Resource
    IsmTaskService ismTaskService;

    public IsmGetNcFileByNumServiceImpl(){}

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception{
        JSONObject result = new JSONObject();
        this.checkAndGetData(businessParams);
        JSONObject resData = this.getNcFileByNum(businessParams.getJSONObject(SignatureConstant.INPUT_PARAMS));
        ismTaskService.deleteTaskByParams(sysCode, serviceCode, serviceCode, null,
                businessParams.getString(SignatureConstant.INPUT_PARAMS));
        result.put("flag", "success");
        result.put("data", resData);
        return result;
    }
    //入参检查
    private void checkAndGetData(JSONObject busParams) throws BusinessMessage{
        JSONObject object = busParams.getJSONObject(SignatureConstant.INPUT_PARAMS);
        String ncNum = object.getString("ncNum");
        String userAccount = object.getString("userAccount");
        if(StringUtil.isEmpty(ncNum)){
            throw new BusinessMessage("请求中缺少ncNum参数，请检查！");
        }
        if(StringUtil.isEmpty(userAccount)){
            throw new BusinessMessage("请求中缺少账户信息（userAccount）参数，请检查！");
        }
    }
    //获取程序清单文件
    private JSONObject getNcFileByNum(JSONObject object) throws Exception{

        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        String ncNum = object.getString("ncNum");
        String userAccount = object.getString("userAccount");
        //用户设置
        IUser user = EtechUserUtil.getUserByAccount(userAccount);
        ContextUtil.setCurrentUser(user);
        String sql = "select ncid from proc_nc where active=1 and ncnum=?";
        List<Map<String,Object>> ncList = slaveJdbcTemplate.queryForList(sql, ncNum);
        if(ncList==null || ncList.size()==0){
            return null;
        }
        File file = ncService.download((Long) ncList.get(0).get("ncid"), null);
        String fileName = file.getName();
        String filePath = null;
        String tempFileId = null;
        sql = "select id_,path_ from sys_file_temp where module_='nc' and name_=? order by id_ desc limit 1";
        List<Map<String,Object>> fileList = slaveJdbcTemplate.queryForList(sql, fileName);
        if(fileList!=null && fileList.size()>0) {
            filePath = fileList.get(0).get("path_").toString();
            tempFileId = fileList.get(0).get("id_").toString();
        }else {//新增
            filePath = fileHandlerService.getFileRelativePath(IdUtil.getSuid() + ".pdf","temp");
            //保存临时文件表
            JSONObject tempObject = new JSONObject();
            tempObject.put("name_", fileName);
            tempObject.put("module_", "nc");
            tempObject.put("path_", filePath);
            tempFileId = webUploaderService.saveTempFile(tempObject);
        }
        //移动文件到临时目录，覆盖原文件
        FileUtil.move(file, FileUtil.file(fileHandlerService.getEtechFileBaseDir() + filePath), true);

        JSONObject dataObj = new JSONObject();
        dataObj.put("file_name", fileName);
        dataObj.put("url", RequestHolder.getUrl() + "/sys/sysFile/preview.html?fileId=" + tempFileId + "&withWatermark=1&audience=drawing");
        return dataObj;
    }

    @Override
    public String methodName(){
        return "getNcFileByNum";
    }
}
